<?php
namespace app\index\model;
use think\Model;
use think\Db;
class Recharge extends Model
{
    public function recharge_artifical($cardnum, $amount, $attach, $worker){
        $cardamount = $this -> update_cardamount("add", $cardnum, $amount);
        if($cardamount){
            //余额更新成功，插入充值记录
            $res = Db::table("laytp_recharge")
                ->insert(array(
                    "cardnum" => $cardnum,
                    "amount" => $amount,
                    "time" => time(),
                    "attach" => $attach,
                    "worker" => $worker,
                ));
            if($res){
                //记录成功
                return $res;
            }else{
                //记录失败，余额回滚
                $cardamount = $this -> update_cardamount("sub", $cardnum, $amount);
                return -1;
            }
        }else{
            //余额更新失败，直接返回
            return -1;
        }
    }

    public function update_cardamount($fn, $cardnum, $amount){
        if($fn == "sub"){$exp = "-";}else{$exp = "+";}
        $res = Db::table("laytp_card")
            ->where("cardnum", $cardnum)
            ->exp("amount", "amount".$exp.$amount)
            ->update();
        return $res;
    }
}